#!/bin/env pypy

"""
Toolkit for the manipulation of BEDGRAPH files.

Usage:
  bedgraph interpolate <bedgraph> <resolution>

Options:
  -h --help      Show this screen.
"""

from __future__ import print_function
import sys, subprocess, docopt, re, os
from pypette import zopen, shell, read_fasta, revcomplement, GenomicFeatures
from pypette import info, error




########################
# BEDGRAPH INTERPOLATE #
########################

def bedgraph_interpolate(bedgraph_path, resolution):
	chr = ''
	pos = 0
	for line in open(bedgraph_path):
		if line[0] == '#': continue
		cols = line[:-1].split('\t')
		
		npos = int(cols[1])    # FIXME: Or maybe between start and stop?
		if cols[0] != chr:
			chr = cols[0]
			pos = npos
			print('%s\t%d\t%s' % (chr, pos, cols[3]))
			continue
		
		while 1:
			if npos == pos + resolution:
				pos += resolution
				print('%s\t%d\t%s' % (chr, pos, cols[3]))
				break
			elif npos > pos + resolution:
				pos += resolution
				print('%s\t%d\t0' % (chr, pos))
			elif npos < pos + resolution:
				info('WARNING: %s:%d not at fixed interval.' % (chr, npos))
				break
		
	
	
	

#######################
# COMMAND LINE PARSER #
#######################

if __name__ == '__main__':
	args = docopt.docopt(__doc__)
	if args['interpolate']:
		bedgraph_interpolate(args['<bedgraph>'], int(args['<resolution>']))
	
